import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {LoginService} from 'app/lib/service/tuike-login.service';
import {LocalStorageService} from "../../lib/service/local-storage.service";
import {OauthService} from "../../lib/service/oauth.service";

export class LoginData {
  code: number;
  data: {
    user: {
      id: number,
      user_uuid: string,
      name: string,
      nick_name: string,
      email: string,
      mobile: string,
      remember_token: string,
      sex: string,
      avatar: string,
      isLock: number,
      lock_time: Date,
      openning_time: Date,
      created_at: Date,
      updated_at: Date,
      remark: string,
      time: string,
    },
    token:{
      "access_token": string,
      "token_type": string,
      "expires_in": number,
      "expires_at": Date
    }
  };
  message: string;
  time: string;
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [LoginService, OauthService,LocalStorageService],
})
export class LoginComponent implements OnInit {

  loginData = new LoginData();

  public username;
  public password;
  alerts;

  constructor(private router: Router,
              private loginService: LoginService,
              private localStorageService: LocalStorageService) {}

  ngOnInit() {
  }

  login() {
    this.loginService.doLoginAdmin(this.username, this.password).subscribe(
      rs => {
        if (rs.code === 2000) {
          this.loginData = rs;
          const time = rs.response_time ? new Date(rs.response_time) : new Date(rs.time);
          const now_time = time.getTime() / 1000;
          this.loginData.data.user.time = now_time + '';
          // 清理之前登录的信息
          this.localStorageService.clearAll();
          // 保存当前的信息
          this.localStorageService.setAdminInfo(this.loginData.data.user);
          this.localStorageService.setToken(this.loginData.data.token);
          return this.redirect();
        } else {
          return this.alerts = [{
            type: 'danger',
            msg: rs.message,
          }];
        }
      },
      err => console.log(err),
    );
  }

  redirect() {
    this.router.navigate(['/tuike']);
    // setInterval(() => {
    //   let sideTree = JSON.parse(window.localStorage.getItem('sideTree'));
    //   console.log(sideTree[0][0]['path']);
    // },1000);
    // console.log('已经登录');

      // this.router.navigate(['/admin/index']);
    // } else {
    //   console.log('未登录');
    // }
  }
}
